<template>
  <el-form ref="form" :class="defaultClass">
    <nb-form
      label="活动名称"
      required=":请输入活动名称"
      placeholder="最多100个字"
      name="name"
      :maxs="100"
      prop="name"
      :disabled="publishStatus"
      v-model="model.name"
      :preview="status === 1"
    ></nb-form>
    <nb-form
      type="select"
      label="活动类型"
      required=":请选择活动类型"
      :options="options"
      name="typeId"
      prop="typeId"
      :defaultKey="defaultKey1"
      v-model="model.typeId"
    ></nb-form>
    <nb-form
      label='活动简介'
      :maxs="300"
      placeholder="最多300字"
      name="summary"
      required
      prop="summary"
      v-model="model.summary"
    ></nb-form>
    <nb-form
      type="datetime"
      label="活动开始时间"
      name="startTime"
      required=":选择活动开始时间"
      v-model="model.startTime"
      prop="startTime"
      :disabled="publishStatus"
      pattern="date|YYYY-MM-DD HH:mm:ss"
    ></nb-form>
    <nb-form
      type="datetime"
      label="活动结束时间"
      name="endTime"
      v-model="model.endTime"
      prop="endTime"
      required=":选择活动结束时间"
      pattern="date|YYYY-MM-DD HH:mm:ss"
    ></nb-form>
    <nb-form
      label="活动地点"
      placeholder="最多100个字"
      name="address"
      :maxs="100"
      v-model="model.address"
    ></nb-form>
    <nb-form
      label="活动邀约人数"
      input="isInteger"
      v-model="model.invitePeopleNum"
      name="invitePeopleNum"
    >
      <div slot="out" style="padding: 0 15px;">人</div>
    </nb-form>

    <nb-form
      label="活动内容"
      name="content"
      type="oneEditor"
      @oneEditor="openEditor"
      v-model="model.content"
    ></nb-form>
    <nb-form
      type="image"
      label="上传图片"
      required=":请上传图片"
      name="file"
      prop="file"
      v-model="model.pictureUrl"
      :maxs="10"
      labelTips="该图用于学院列表封面，建议上传 60*60 尺寸的图片，最大允许10M"
      :inline="false"
      upload
    ></nb-form>
    <nb-form
      type="video"
      label="视频附件"
      ref="formVideo"
      v-model="videoName"
      valueNum="2"
      :maxs="1024"
      :inline="false"
      labelTips="最多允许上传2个视频，<br>只允许上传AVI、 MP4、 WMV 、 MOV、FLV格式的视频文件，<br>单个视频最大允许1G"
    ></nb-form>
    <span class="span-tips"></span>
    <nb-form
      label="活动所属部门"
      required
      prop="deptCode"
      @click="clickDepart(true)"
      type="click"
      :disabled="publishStatus"
      placeholder="请选择活动所属部门"
      v-model="departSelect"
    ></nb-form>
    <nb-form
      label="活动负责人"
      boxed
      name="manager"
      v-model="model.manager"
    >
      <div class="manager-wrapper" slot="box">
        <nb-department v-model="managerName" @close="tagClose" @getManager="getManager"></nb-department>
      </div>
    </nb-form>
    <nb-form
      label="可见范围配置"
      required=":请选择可见范围"
      prop="scope"
      labelTips="客户、独立理财顾问的可见范围是在其理财顾问是否可见的基础之上设置的。<br/>例如：某内部理财顾问不可见产品，则其名下的独立理财顾问和客户都不可见。"
      boxed
      v-model="model.scope"
      :inline="false"
    >
      <div slot="box" class="scope-set-wrapper" v-if="!showScopeStatus">
        全部可见
        <span @click="setScoped">设置</span>
      </div>
    </nb-form>
    <div
      v-if="showScopeStatus"
      class="show-scope-status"
    >
      <nb-form
        label="内部理财顾问"
        boxed
        :inline="false"
      >
        <div class="scope-box-wrapper" slot="box">
          <div
            class="scope-item"
            v-for="item in faList"
            :key="item.id + item.name"
          >{{item.name}}</div>
        </div>
      </nb-form>
      <nb-form
        label="独立理财顾问"
        boxed
        :inline="false"
      >
        <div class="scope-box-wrapper" slot="box">
          <div
            class="scope-item"
            v-for="item in ifaList"
            :key="item.id"
          >{{item.name}}</div>
        </div>
      </nb-form>
      <nb-form
        label="客户"
        boxed
        :inline="false"
      >
        <div class="scope-box-wrapper" slot="box">
          <div
            class="scope-item"
            v-for="item in customerList"
            :key="item.id"
          >{{item.name}}</div>
        </div>
      </nb-form>
      <div class="modify-scope" @click="setScoped(true)">修改</div>
    </div>

    <nb-form
      label="分享配置"
      type="radio"
      required
      prop="enableShareCfg"
      :checkItem="shareItem"
      v-model="enableShareCfg"
    ></nb-form>
    <nb-form
      v-if="enableShareCfg === '1'"
      label="分享渠道"
      required=":请选择分享渠道"
      type="checkbox"
      v-model="shareCfg"
      name="shareCfg"
      prop="shareCfg"
      :checkItem="shareValue"
    ></nb-form>
    <div class="self-footer" style="padding-bottom: 20px;">
      <nb-button large type="plain" @click="goBack">取 消</nb-button>
      <nb-button large type="primary" @click.stop="confirm">确定</nb-button>
    </div>
    <select-job
      ref="selectJob"
    ></select-job>
    <select-tab
      ref="selectTab"
      @confirm="confirmTab"
    ></select-tab>
  </el-form>
</template>

<script>
  import NbForm from '@/components/nb-form.vue'
  import FdForm from '@/components/fd-form.vue'
  import Mixin from '@/common/mixin'
  import NbDepartment from '@/components/nb-department.vue'
  import NbStep from '@/components/nb-step'
  import NbDrawer from '@/components/nb-drawer'
  import SelectJob from '@/components/select-job'
  import SelectTab from '@/components/select-tab'
  import {fieldArr, formDataObject, handleScope, isInteger, isMoney} from '@/common/utils'
  import MixinEdit from '@/common/mixinEdit'
  export default {
    data () {
      return {
        checkItem: [{
          label: '客户',
          value: '1'
        }, {
          label: '内部咨询顾问',
          value: '2'
        }, {
          label: '外部咨询顾问',
          value: '4'
        }],
        options: [],
        department: [],
        defaultKey1: {
          label: 'name',
          value: 'id'
        },
        defaultKey2: {
          label: 'name',
          value: 'code'
        },
        scopes: [],
        imageUrl: '',
        model: {
          scope: '-1',
          enableShareCfg: '1',
          content: '',
          giftNum: '',
          giftSurplusNum: '',
          giftAmount: '',
          giftName: '',
          giftType: '',
          actualCost: '',
          budgetCost: '',
          giftSendNum: ''
        },
        _id: '',
        enableShareCfg: '1',
        departSelect: [],
        faDept: [],
        shareItem: [{
          label: '启用',
          value: '1'
        }, {
          label: '禁用',
          value: '0'
        }],
        shareValue: [{
          label: '微信',
          value: 1
        }, {
          label: '朋友圈',
          value: 2
        }, {
          label: 'QQ',
          value: 4
        }],
        scopedItem: [{
          label: '全部可见',
          value: '-1'
        }, {
          label: '部分可见',
          value: '0',
          slot: '所选部门、职位、标签取并集可见'
        }],
        ifaItem: [{
          label: '全部可见',
          value: '-1'
        }, {
          label: '全部不可见',
          value: '-2'
        }],
        customItem: [{
          label: '全部可见',
          value: '-1'
        }, {
          label: '部分可见',
          value: '0'
        }, {
          label: '全部不可见',
          value: '-2'
        }],
        shareCfg: [1, 2, 4],
        stepActivity: 1,
        stepTipsMap: {
          1: '',
          2: '注：独立理财顾问的可见范围是在其内部理财顾问是否可见的基础之上设置的',
          3: '注：客户的可见范围是在其内部理财顾问或者独立理财顾问是否可见的基础之上设置的'
        },
        departType: true,
        faPosition: [],
        faTag: [],
        customerTag: [],
        faScope: '-1',
        ifaScope: '-1',
        customerScope: '-1',
        faList: [],
        ifaList: [],
        customerList: [],
        showScopeStatus: false,
        visibleScope: {},
        status: '',
        managerName: this.detailData && this.detailData.managerName ? this.detailData.managerName : '',
        videoName: [],
        publishStatus: false
      }
    },
    props: {
      defaultClass: {
        type: String,
        default: 'form-center-wrapper'
      },
      detailData: Object
    },
    mixins: [Mixin, MixinEdit],
    components: {
      NbForm,
      FdForm,
      NbDepartment,
      NbStep,
      NbDrawer,
      SelectJob,
      SelectTab
    },
    watch: {
      detailData () {
        this.$nextTick(() => {
          this.initData()
        })
      },
      'enableShareCfg': {
        deep: true,
        handler (val) {
        }
      }
    },
    computed: {
      stepTips () {
        return this.stepTipsMap[this.stepActivity]
      },
      cancelText () {
        return this.stepActivity === 1 ? '返回' : '上一步'
      },
      successText () {
        return this.stepActivity !== 3 ? '下一步' : '确定'
      }
    },
    methods: {
      initData () {
        if (this.detailData) {
          this.model = this.detailData
          this.publishStatus = Boolean(this.detailData.releaseTime)
          this.model.startTime = new Date(this.detailData.startTime)
          this.model.endTime = new Date(this.detailData.endTime)
          if (this.detailData.shareCfg !== null) {
            this.enableShareCfg = this.detailData.shareCfg + ''
          } else {
            this.enableShareCfg = '1'
          }
          this.model.scope = this.detailData.scope + ''
          this.shareCfg = handleScope(this.detailData.shareConfigValue)
          this.departSelect.push({
            code: this.detailData.deptCode,
            name: this.detailData.deptName
          })
          this._id = this.detailData.id
          this.status = this.detailData.status
          this.faPosition = this.detailData.scopeVo.faPosition
          this.faTag = this.detailData.scopeVo.faTag
          this.faDept = this.detailData.scopeVo.faDept
          this.customerTag = this.detailData.scopeVo.customerTag
          if (this.detailData.scopeVo.faScope === null) {
            this.faScope = '0'
            if (this.model.scope === '-1') {
              this.faScope = '-1'
            }
          } else {
            this.faScope = this.detailData.scopeVo.faScope + ''
          }
          if (this.detailData.scopeVo.ifaScope === null) {
            this.ifaScope = '-2'
            if (this.model.scope === '-1') {
              this.ifaScope = '-1'
            }
          } else {
            this.ifaScope = this.detailData.scopeVo.ifaScope + ''
          }
          if (this.detailData.scopeVo.customerScope === null) {
            this.customerScope = '0'
            if (this.model.scope === '-1') {
              this.customerScope = '-1'
            }
          } else {
            this.customerScope = this.detailData.scopeVo.customerScope + ''
          }
          this.videoName = []
          if (this.detailData.videos && this.detailData.videos.length) {
            this.detailData.videos.map(item => {
              this.videoName.push({
                name: item.fileName,
                url: decodeURIComponent(item.fileUrl)
              })
            })
          }
          this.handleScopeData()
        }
      },
      confirm () {
        let value = this.validator(this.$refs.form)
        if (!value) {
          let _data = new FormData(this.$refs.form.$el)
          _data.append('scope', this.model.scope)
          _data.append('enableShareCfg', this.enableShareCfg)
          if (this.model.scope === '0' || this.model.scope === '-3') {
            formDataObject('visibleScope', _data, this.visibleScope)
          }
          _data.append('deptCode', this.departSelect[0].code)
          _data.append('inputVideos', this.$refs.formVideo.getVideo())
          if (this._id) {
            _data.append('id', this._id)
          }
          if (this.model.invitePeopleNum && !isInteger(this.model.invitePeopleNum)) {
            return this.$message.warning('请检查活动邀约人数数据格式！')
          }
          if (this.model.budgetCost && !isMoney(this.model.budgetCost)) {
            return this.$message.warning('请检查活动预算费用格式！')
          }
          if (this.model.actualCost && !isMoney(this.model.actualCost)) {
            return this.$message.warning('请检查活动实际费用格式！')
          }
          if (this.model.giftAmount && !isMoney(this.model.giftAmount)) {
            return this.$message.warning('请检查礼品总金额格式！')
          }

          if (this.model.giftSurplusNum && !isInteger(this.model.giftSurplusNum)) {
            return this.$message.warning('请检查输入数据格式！')
          }
          if (this.model.giftNum && !isInteger(this.model.giftNum)) {
            return this.$message.warning('请检查输入数据格式！')
          }
          if (this.model.giftSendNum && !isInteger(this.model.giftSendNum)) {
            return this.$message.warning('请检查输入数据格式！')
          }

          this.$store.dispatch(this._id ? 'UPDATE_ACTIVITY' : 'CREATE_ACTIVITY', _data).then(res => {
            if (res.success) {
              this.$message.success(this._id ? '修改成功！' : '创建成功！')
              setTimeout(() => {
                if (this._id) {
                  this.$emit('over')
                } else {
                  this.back()
                }
              }, 1000)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      },
      async init () {
        await this.$store.dispatch('ACTIVITY_LIST', {param: {}}).then(res => {
          if (res.success) {
            this.options = res.data.list
          } else {
            this.$message.error(res.msg)
          }
        })
        await this.$store.dispatch('DEPARTMENT_LIST', {param: {}}).then(res => {
          if (res.success) {
            this.department = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      getManager (data) {
        this.model.manager = data.id
        this.managerName = data.name
      },
      tagClose () {
        this.model.manager = ''
        this.managerName = ''
      },
      clickDepart (type) {
        this.departType = type
        if (type) {
          this.$refs.selectDepart.show(this.departSelect)
        } else {
          this.$refs.selectDepart.show(this.faDept)
        }
      },
      selectDepartEd (data) {
        if (this.departType) {
          this.departSelect = data
        } else {
          this.faDept = data
        }
      },
      setScoped (type) {
        if (type) {
          this.stepActivity = 1
        }
        this.$refs.drawer.show()
      },
      nextStep () {
        if (this.faScope === '0' && !this.faDept.length && !this.faPosition.length && !this.faTag.length) {
          this.$message.warning('请选择部分可见的部门、职位或标签！')
          return
        }
        if (this.customerScope === '0' && !this.customerTag.length && this.stepActivity === 3) {
          this.$message.warning('请选择可见标签！')
          return
        }
        if (this.stepActivity === 3) {
          this.model.scope = '0'
          if (this.faScope === '-1' && this.ifaScope === '-1' && this.customerScope === '-1') {
            this.model.scope = '-3'
          }
          this.handleScopeData()
          this.$refs.drawer.hide()
          return
        }
        this.stepActivity += 1
      },
      backStep () {
        if (this.stepActivity === 1) {
          this.$refs.drawer.hide()
          return
        }
        this.stepActivity -= 1
      },
      handleScopeData () {
        this.faList = []
        this.ifaList = []
        this.customerList = []
        if (this.faScope === '-1' || this.model.scope === '-1') {
          this.faList.push({name: '全部可见', id: -1})
          this.visibleScope.faDept = []
          this.visibleScope.faPosition = []
          this.visibleScope.faTag = []
        } else {
          this.faList = this.faDept.concat(this.faPosition)
          this.faList = this.faList.concat(this.faTag)
          this.visibleScope.faDept = fieldArr(this.faDept)
          this.visibleScope.faPosition = fieldArr(this.faPosition)
          this.visibleScope.faTag = fieldArr(this.faTag)
        }
        if (this.ifaScope === '-1' || this.model.scope === '-1') {
          this.ifaList.push({name: '全部可见', id: -1})
        } else {
          this.ifaList.push({name: '全部不可见', id: -2})
        }
        if (this.customerScope === '-1' || this.model.scope === '-1') {
          this.customerList.push({name: '全部可见', id: -1})
          this.visibleScope.customerTag = []
        } else if (this.customerScope === '0' || this.customerScope === 'null') {
          this.customerList = this.customerTag
          this.visibleScope.customerTag = fieldArr(this.customerTag)
        } else {
          this.customerList.push({name: '全部不可见', id: -2})
          this.visibleScope.customerTag = []
        }
        this.visibleScope.faScope = this.faScope
        this.visibleScope.ifaScope = this.ifaScope
        this.visibleScope.customerScope = this.customerScope
        this.showScopeStatus = true
      },
      clickJob () {
        this.$refs.selectJob.show(this.faPosition)
      },
      clickTab () {
        this.$refs.selectTab.show(this.faTag, '1')
      },
      customTab () {
        this.$refs.selectTab.show(this.customerTag, '2', 2)
      },
      confirmTab (data, type) {
        if (type === '1') {
          this.faTag = []
          this.faTag = data
        } else {
          this.customerTag = []
          this.customerTag = data
        }
      },
      goBack () {
        if (this._id) {
          this.$emit('over')
        } else {
          this.back()
        }
      },
      openEditor () {
        this.$refs.nbEditor.show(this.model.content)
      },
      saveEditor (val) {
        this.model.content = val
      }
    },
    mounted () {
      this.init()
      this.$nextTick(() => {
        this.initData()
      })
    }
  }
</script>

<style lang="scss">
  .manager-wrapper{
    display: flex;
    align-items: center;
    .el-tag{
      margin-left: 10px;
      margin-top: 2px;
    }
  }
  .scope-set-wrapper{
    -webkit-appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #d8dce5;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #5a5e66;
    /* display: inline-block; */
    font-size: inherit;
    min-height: 40px;
    line-height: 37px;
    outline: 0;
    padding: 0 15px;
    span{
      cursor: pointer;
      color: #1F8EFA;
      float: right;
    }
  }
  .scope-box-wrapper{
    display: flex;
    flex-wrap: wrap;
    .scope-item{
      border: 1px solid #ccc;
      border-radius: 4px;
      height: 38px;
      line-height: 38px;
      text-align: center;
      padding: 0 12px;
      color: #333;
      margin: 5px 15px 5px 0;
    }
    .scope-btn{
      width: 38px;
      padding: 0;
      cursor: pointer;
    }
  }
  .show-scope-status{
    width: 100%;
    .modify-scope{
      margin: 0 20px 20px;
      border-radius: 4px;
      border: 1px solid #d8dce5;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      color: #1F8EFA;
      font-size: inherit;
      min-height: 40px;
      line-height: 37px;
      outline: 0;
      padding: 0 15px;
      text-align: center;
      cursor: pointer;
    }
    .el-form-item{
      margin-bottom: 10px;
    }
  }
</style>
